<template>
  <div class='searchSuggest-container'>
    <van-cell icon="search" is-link v-for="(item,index) in suggestList" :key="index"
      @click="$emit('link-search',item)">
      <div slot="title" v-html="highLight(item)"></div>
    </van-cell>
  </div>
</template>
<script>
import { getSuggestions } from '@/api/search.js';
import { debounce } from 'lodash'; // 按需加载
export default {
  name: 'searchSuggestPage',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestList: [],
    };
  },
  created() {},
  computed: {},
  watch: {
    searchText: {
      // handler(val) {
      //   console.log(val);
      //   // 请求数据
      //   this.loadSuggest(val)
      // },
      // 创建一个 debounced（防抖动）函数，
      // 该函数会从上一次被调用后，延迟 wait 毫秒后调用 func 方法
      handler: debounce(function (val) {
        this.loadSuggest(val);
      }, 300),
      immediate: true, // 在侦听开始后立即调用一次
    },
  },
  methods: {
    // 文字高亮处理
    highLight(text) {
      const highLightStr = `<span style="color:red;">${this.searchText}</span>`;
      if (!text) return;
      /**
       * 正则表达式构造函数:
       * 参数一:匹配模式字符串
       * 参数二:匹配模式,要写在字符串中
       */
      let reg = new RegExp(this.searchText, 'gi');
      return text.replace(reg, highLightStr);
    },
    loadSuggest(val) {
      getSuggestions(val)
        .then((res) => {
          console.log(res);
          this.suggestList = res.options;
        })
        .catch((err) => {
          this.$toast(err || '数据请求失败!请稍后重试');
        });
    },
  },
};
</script>
<style lang='less' scoped>
</style>
